package com.example.demo;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DynamicClassLoader extends URLClassLoader {

    private final Path classPath;

    public DynamicClassLoader() {
        // 打破双亲委派
        super(new URL[0]);
        this.classPath = Paths.get(RuleClassUtils.getClassPath());

    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] classBytes = loadClassBytes(name);
            return defineClass(name, classBytes, 0, classBytes.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("Failed to load class " + name, e);
        }
    }


    private byte[] loadClassBytes(String name) throws IOException {
        String className = name.replace('.', '/') + ".class";
        Path classFile = classPath.resolve(className);
        return Files.readAllBytes(classFile);
    }

}
